package com.lgq.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.lgq.dao.DepartmentDAO;
import com.lgq.model.College;
import com.lgq.model.Department;
import com.lgq.util.Page;
@Component("departmentDAO")
public class DepartmentDAOImpl implements DepartmentDAO {
	private HibernateTemplate hibernateTemplate;
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public Page<Department> getAllDepartment(int currentPage, int numPerPage) {
		Page<Department> page=new Page<Department>(currentPage,numPerPage);
		page.setTotalCount(Integer.parseInt((Long) getHibernateTemplate().find("select count(*) from Department").get(0)+""));
		String hql="from Department";
		page.setList(getListForPage(hql,(page.getCurrentPage()-1)*numPerPage, numPerPage));
		return page;
	}

	@Override
	public Page<Department> findByName(int currentPage, int numPerPage,
			String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Department findById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Department findByName(String name) {
		List<Department> depts=this.hibernateTemplate.find("from Department d where d.name='"+name+"'");
		if(depts.size()>0)
		{
			return depts.get(0);
		}else
		{
			return null;
		}
	}

	@Override
	public boolean updateDepartment(Department department) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteDepartment(Department department) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean addDepartment(Department department) {
		try
		{
			this.getHibernateTemplate().save(department);
			return true;
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}
	public List getListForPage(final String hql, final int offset,
			final int length) {

			List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
			throws HibernateException, SQLException {
			Query query = session.createQuery(hql);
			query.setFirstResult(offset);
			query.setMaxResults(length);
			List list = query.list();
			return list;
			}
			});
			return list;
	}
}
